from django.db.models import F, Case, When

from finance.models import Prepayment
from sale.models import SaleOrder


def decrease_sale_order_amounts(objs):
    """减少出库单已付金额和修改付款状态"""
    for obj in objs:
        if obj.category == 1:
            remove_prepay_amount(obj)
        else:
            decrease_sale_order_amount(obj)


def decrease_sale_order_amount(obj):
    """减少出库单已付金额和修改付款状态"""
    SaleOrder.objects.filter(id=obj.sale_order_id) \
        .update(
        amount=F("amount") - obj.amount,
        status=Case(When(total_amount__lte=F("amount"), then=1), default=0)
    )


def remove_prepay_amount(obj):
    code = obj.receipt_order.code + '预收款'
    Prepayment.objects.filter(code=code).delete()
